package rstplus;

/*
 * RST - Russian SMS transliterator
 * Copyleft 2011
 * Author: Alexey Shat'ko (Алексей Шатько), rstapp@yandex.ru
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this source code (in file copying.txt); if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */


import javax.microedition.rms.*;
import java.util.Vector;
import java.util.Enumeration;
import java.io.*;
import java.util.Calendar;
import java.util.Date;

public final class SavedDraftsStorage {

    private static final String RS_NAME = "rstplus.pb";
    private static RecordStore rs = null;
    private static int rsOpen = 0;

    private static void rsOpen() throws RecordStoreException {
        if (rsOpen <= 0) {
            rs = RecordStore.openRecordStore(RS_NAME, true);
            rsOpen = 1;
        } else {
            rsOpen++;
        }
    }

    private static void rsClose() throws RecordStoreException {
        if (rsOpen > 1) {
            rsOpen--;
        } else if (rsOpen == 1) {
            rs.closeRecordStore();
            rs = null;
            rsOpen = 0;
        }
    }
    private static Vector items = null;

    public static void load() throws RecordStoreException {
        items = new Vector();
        rsOpen();
        try {
            RecordEnumeration re = rs.enumerateRecords(null, null, false);
            try {
                while (re.hasNextElement()) {
                    int id = re.nextRecordId();
                    byte[] record = rs.getRecord(id);
                    try {
                        DataInputStream dis = new DataInputStream(new ByteArrayInputStream(record));
                        try {
                            String text = dis.readUTF();
                            byte[] dateRecord = new byte[SerializableDate.SERIALIZED_SIZE];
                            dis.read(dateRecord, 0, dateRecord.length);
                            SerializableDate date = new SerializableDate(dateRecord);
                            SavedDraft item = new SavedDraft(text, false, date, id);
                            items.addElement(item);
                        } finally {
                            dis.close();
                        }
                    } catch (IOException exc) {
                        throw new RuntimeException();
                    }
                }
            } finally {
                re.destroy();
            }
        } finally {
            rsClose();
        }
        sort();
    }

    private static void sort() {
        int count = items.size();
        for (int i = 0; i < count - 1; i++) {
            int k = i;
            SavedDraft ii = (SavedDraft) items.elementAt(i);
            SavedDraft ki = ii;
            for (int j = i + 1; j < count; j++) {
                SavedDraft ji = (SavedDraft) items.elementAt(j);
                if (ji.getDate().compareTo(ki.getDate()) < 0) {
                    ki = ji;
                    k = j;
                }
            }
            if (i != k) {
                items.setElementAt(ki, i);
                items.setElementAt(ii, k);
            }
        }
    }

    public static void unload() {
        items = null;
    }

    public static int getItemsCount() {
        return items.size();
    }

    public static SavedDraft getItem(int index) {
        return (SavedDraft) items.elementAt(index);
    }

    public static String getFullText(int index) throws RecordStoreException {
        SavedDraft item = (SavedDraft) items.elementAt(index);
        if (item.isFullText()) {
            return item.getText();
        }
        int id = item.getId();
        rsOpen();
        byte[] record = null;
        try {
            record = rs.getRecord(id);
        } finally {
            rsClose();
        }
        try {
            DataInputStream dis = new DataInputStream(new ByteArrayInputStream(record));
            try {
                String text = dis.readUTF();
                item.setText(text, true);
                return text;
            } finally {
                dis.close();
            }
        } catch (Exception exc) {
            throw new RuntimeException();
        }
    }

    public static void addRecord(String text) throws RecordStoreException {
        rsOpen();
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            try {
                DataOutputStream dos = new DataOutputStream(baos);
                try {
                    dos.writeUTF(text);
                    Date date = new Date();
                    SerializableDate sdate = new SerializableDate(date);
                    byte[] dateRecord = sdate.toByteArray();
                    dos.write(dateRecord, 0, dateRecord.length);
                } finally {
                    dos.close();
                }
            } catch (IOException exc) {
                throw new RuntimeException();
            }
            byte[] record = baos.toByteArray();
            rs.addRecord(record, 0, record.length);
            if (items != null) {
                load();
            }
        } finally {
            rsClose();
        }
    }

    public static void deleteRecord(int index) throws RecordStoreException {
        int id = ((SavedDraft) items.elementAt(index)).getId();
        rsOpen();
        try {
            rs.deleteRecord(id);
        } finally {
            rsClose();
        }
        items.removeElementAt(index);
    }

    public static void deleteAll() throws RecordStoreException {
        rsOpen();
        try {
            while (items.size() > 0) {
                deleteRecord(items.size() - 1);
            }
        } finally {
            rsClose();
        }
    }

    public static final class SavedDraft {

        private boolean isFullText;
        private String text;
        private SerializableDate date;
        private int id;
        private static final int TRIM_LEN = 20;

        public SavedDraft(String text, boolean isFullText, SerializableDate date, int id) {
            this.isFullText = isFullText;
            this.text = isFullText ? text : trimText(text);
            this.id = id;
            this.date = date;
        }

        public String getText() {
            return text;
        }

        public String getShortText() {
            return isFullText ? trimText(text) : text;
        }

        public boolean isFullText() {
            return isFullText;
        }

        public void setText(String text, boolean isFullText) {
            this.isFullText = isFullText;
            this.text = isFullText ? text : trimText(text);
        }

        public SerializableDate getDate() {
            return date;
        }

        public int getId() {
            return id;
        }

        public void setId(int value) {
            id = value;
        }

        public static String trimText(String text) {
            int len = text.length();
            if (len <= TRIM_LEN) {
                return text;
            } else {
                return text.substring(0, TRIM_LEN) + "...";
            }
        }
    }
}
